import sys
import getEntrez

if (len(sys.argv) != 3):
        print "Requires pathway.xgmml name ie fatty_acide_oxidation.xgmml fao"
        sys.exit(-1)

xgmml = sys.argv[1]
xname = sys.argv[2]

ins = open(xgmml, "r" )
xgarray = []
for line in ins:
	xgarray.append( line )

adipoflux_ids = {}

"""
f = open("../data/recon1entrez2symbol.txt", "r")
hg19dic = {}
for line in f.readlines():
        tk = line.strip().split()
        hg19dic[tk[0]] = tk[1]
f.close()

rec = ""
rec2 = ""
adipoflux_ids = {}

f2 = open("../data/recon1entrez2symbol.txt", "r")
for line in f2.readlines():
        gene = line.strip().split("\t")[1]
        ekey = line.strip().split("\t")[0]
        if (hg19dic.get(gene) == None):
                print gene + " not found in hg19.tsv"
        else:
                pos = hg19dic.get(gene)
		adipoflux_ids[ekey] = gene
                rec2 = rec2 + "'%s':'%s',\n" %(ekey, gene)
                rec = rec + "'%s':'%s',\n" %(gene, pos)
f2.close()

print str(len(adipoflux_ids)) + " fatgene hash" 
<node label="2181.2" id="-115">
    <att type="string" name="NodeTypes" value="gene"/>

  <node label="2181.1" id="-112">
    <att type="string" name="NodeTypes" value="gene"/>
"""

newids = {}
#put old ides in new id hash, and then replace all instance of -id number
#"-115" include quotes in hash key
for ar in range(len(xgarray)-1):
	xline = xgarray[ar]
	if (xline.find('value="gene"') != -1):
		idline = xgarray[ar-3].strip()
		print xgarray[ar-3] + xline
		label = idline.split('label="')[1].split('"')[0]
		#update label later too
		id = label.split(".")[0]
		minusid = idline.split("id=")[1][:-1]
		genename = getEntrez.fetch('human', id)
		if (genename != "na"):
			genename = genename.split(":")[1]	
			newids[minusid] = id#label.replace(".","")
			print "oldid %s newid %s" %(minusid, label) 
			xgarray[ar-3] = '<node label="%s" id="%s">\n' %(genename, xname + "_" + id) #label.replace(".",""))		
		else:
			print "id %s not found" % id	
		print xgarray[ar-3] + xline

fout = open(xname + "_phatviz.xgmml", "w")
for av in range(len(xgarray)):
	line = xgarray[av].strip()
	for tk in newids:
		if (line.find(tk) != -1):
			line = line.replace(tk, '"' + xname + '_' + newids[tk].replace(".","") + '"')
			#print line + " " + tk + " replaced by " + newids[tk]
			continue
	fout.write(line + "\n")
fout.close()	
